import { defineStore } from 'pinia';
import type { RouteRecordRaw } from 'vue-router';

import type { RouteItem } from '@/api/model/permissionModel';
import { ROLES } from '@/constants';
import router from '@/router';
import { store, useUserStore } from '@/store';
import { transformObjectToRoute } from '@/utils/route';

export const usePermissionStore = defineStore('permission', {
  state: () => ({
    whiteListRouters: ['/login'],
    routers: [] as any,
    removeRoutes: [] as any,
    asyncRoutes: [] as any,
  }),
  actions: {
    async initRoutes() {
      const accessedRouters = this.asyncRoutes;

      // // 在菜单展示全部路由
      //this.routers = [...homepageRouterList, ...accessedRouters, ...fixedRouterList];
      // 在菜单只展示动态路由和首页
      //this.routers = [...homepageRouterList, ...accessedRouters];
      // // 在菜单只展示动态路由
      this.routers = [...accessedRouters];
    },
    async buildAsyncRoutes() {
      try {
        const user = await useUserStore().userInfo;
        console.log(`user:`, user);
        // 兼容后端将角色改为字符串数组的返回结构，例如：["PATIENT","DOCTOR","ADMIN","SUPER_ADMIN"]
        // 仅用于菜单展示：判断是否为管理员或更高（ADMIN/SUPER_ADMIN）以及是否为超级管理员（SUPER_ADMIN）
        const roles = (user as any).role as string[];
        const admin = roles.includes(ROLES.ADMIN);
        const superAdmin = roles.includes(ROLES.SUPER_ADMIN);
        // 发起菜单权限请求 获取菜单列表
        // const asyncRoutes: Array<RouteItem> = (await getMenuList()).list;
        const asyncRoutes: Array<RouteItem> = [
          {
            path: '/home',
            name: 'Home',
            component: 'LAYOUT',
            redirect: '/home/index',
            meta: {
              title: { zh_CN: '首页', en_US: 'Home' },
              icon: 'home',
              single: true,
            },
            children: [
              {
                path: 'index',
                name: 'HomeIndex',
                component: () => import('@/pages/home/index.vue'),
                meta: {
                  title: { zh_CN: '首页', en_US: 'Home' },
                },
              },
            ],
          },
          {
            path: '/guide',
            name: 'guide',
            component: 'LAYOUT',
            redirect: '/guide/index',
            meta: {
              title: { zh_CN: '指南管理', en_US: 'Guide Management' },
              icon: 'book',
            },
            children: [
              {
                path: 'index',
                name: 'GuideIndex',
                component: () => import('@/pages/guide/index.vue'),
                meta: {
                  title: { zh_CN: '指南管理', en_US: 'Guide Management' },
                },
              },
              {
                path: 'audit',
                name: 'GuideAudit',
                component: () => import('@/pages/guide/GuideAudit.vue'),
                // 仅管理员或超级管理员可见
                meta: { title: '指南审核', hidden: admin ? false : true },
              },
              {
                path: 'simpleList',
                name: 'GuideSimpleList',
                component: () => import('@/pages/guide/GuideSimpleList.vue'),
                meta: { title: '指南简要列表', hidden: true },
              },
              {
                path: 'category',
                name: 'GuideCategory',
                component: () => import('@/pages/guide/category.vue'),
                meta: {
                  title: { zh_CN: '指南类别', en_US: 'Guide Category' },
                  // 仅超级管理员可见
                  hidden: superAdmin ? false : true,
                },
              },
              {
                path: 'add',
                name: 'GuideAdd',
                component: () => import('@/pages/guide/GuideAdd.vue'),
                meta: { title: '新增指南', hidden: true },
              },
              {
                path: 'detail',
                name: 'GuideDetail',
                component: () => import('@/pages/detail/guide/GuideDetail.vue'),
                meta: { title: '指南详情', hidden: true },
              },
            ],
          },
          {
            path: '/employee',
            name: 'employee',
            component: 'LAYOUT',
            redirect: '/employee/index',
            meta: {
              title: { zh_CN: '人员管理', en_US: 'Employee Management' },
              icon: 'user-circle',
              // 仅管理员或超级管理员可见
              hidden: admin ? false : true,
            },
            children: [
              {
                path: 'index',
                name: 'EmployeeIndex',
                component: () => import('@/pages/employee/index.vue'),
                meta: { title: { zh_CN: '人员管理', en_US: 'Employee Management' } },
              },
            ],
          },
          {
            path: '/employee/edit/:id',
            name: 'EmployeeEdit',
            component: () => import('@/pages/employee/EmployeeEdit.vue'),
            meta: {
              title: { zh_CN: '编辑员工', en_US: 'Edit Employee' },
              hidden: true, // 不在菜单显示
            },
          },
          {
            path: '/authentication',
            name: 'authentication',
            component: 'LAYOUT',
            redirect: '/authentication/index',
            meta: {
              title: { zh_CN: '认证申请管理', en_US: 'Authentication Management' },
              icon: 'book',
              // 仅管理员或超级管理员可见
              hidden: admin ? false : true,
            },
            children: [
              {
                path: 'index',
                name: 'AuthenticationIndex',
                component: () => import('@/pages/authentication/index.vue'),
                meta: {
                  title: { zh_CN: '认证申请管理', en_US: 'Authentication Management' },
                },
              },
            ],
          },
          {
            path: '/serviceItemRequest',
            name: 'serviceItemRequest',
            component: 'LAYOUT',
            redirect: '/serviceItemRequest/index',
            meta: {
              title: { zh_CN: '项目申请管理', en_US: 'Service Item Request Management' },
              icon: 'book',
              // 仅管理员或超级管理员可见
              hidden: admin ? false : true,
            },
            children: [
              {
                path: 'index',
                name: 'ServiceItemRequestIndex',
                component: () => import('@/pages/serviceItemRequest/index.vue'),
                meta: { title: { zh_CN: '项目申请管理', en_US: 'Service Item Request Management' } },
              },
            ],
          },
          {
            path: '/order',
            name: 'order',
            component: 'LAYOUT',
            redirect: '/order/index',
            meta: {
              title: { zh_CN: '订单管理', en_US: 'Order Management' },
              icon: 'book',
              hidden: admin ? false : true,
            },
            children: [
              {
                path: 'index',
                name: 'OrderIndex',
                component: () => import('@/pages/order/index.vue'),
                meta: { title: { zh_CN: '订单管理', en_US: 'Order Management' } },
              },
            ],
          },
          {
            path: '/suggestion',
            name: 'suggestion',
            component: 'LAYOUT',
            redirect: '/suggestion/index',
            meta: {
              title: { zh_CN: '建议管理', en_US: 'Suggestion Management' },
              icon: 'book',
              // 仅管理员或超级管理员可见
              hidden: admin ? false : true,
            },
            children: [
              {
                path: 'index',
                name: 'suggestionIndex',
                component: () => import('@/pages/suggestion/index.vue'),
                meta: { title: { zh_CN: '建议管理', en_US: 'Suggestion Management' } },
              },
            ],
          },
          {
            path: '/detail',
            name: 'detail',
            component: 'LAYOUT',
            redirect: '/detail/guide',
            meta: {
              title: {
                zh_CN: '详情页',
                en_US: 'Detail',
              },
              icon: 'layers',
            },
            children: [
              {
                path: 'guide',
                name: 'GuideLine',
                component: () => import('@/pages/detail/guide/index.vue'),
                meta: {
                  title: {
                    zh_CN: '指南详情页',
                    en_US: 'Guideline Detail',
                  },
                },
              },
            ],
          },
          {
            path: '/user',
            name: 'user',
            component: 'LAYOUT',
            redirect: '/user/index',
            meta: {
              title: { zh_CN: '个人中心', en_US: 'User Center' },
              icon: 'user-circle',
              single: true,
            },
            children: [
              {
                path: 'index',
                name: 'UserIndex',
                component: () => import('@/pages/user/index.vue'),
                meta: {
                  title: { zh_CN: '个人中心', en_US: 'User Center' },
                },
              },
            ],
          },
          {
            path: '/dynamicDemo',
            name: 'DynamicDemo',
            component: () => import('@/pages/dynamicDemo.vue'),
            meta: { title: { zh_CN: '动态表单', en_US: 'Dynamic Form' } },
          },
        ];
        this.asyncRoutes = transformObjectToRoute(asyncRoutes);
        await this.initRoutes();
        return this.asyncRoutes;
      } catch (error) {
        throw new Error("Can't build routes", error);
      }
    },
    async restoreRoutes() {
      // 不需要在此额外调用initRoutes更新侧边导肮内容，在登录后asyncRoutes为空会调用
      this.asyncRoutes.forEach((item: RouteRecordRaw) => {
        if (item.name) {
          router.removeRoute(item.name);
        }
      });
      this.asyncRoutes = [];
    },
  },
});

export function getPermissionStore() {
  return usePermissionStore(store);
}
